package se.chalmers.tda366.crumble.backgroundthreads;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import se.chalmers.tda366.crumble.core.IArticle;
import se.chalmers.tda366.crumble.core.IFeed;
import se.chalmers.tda366.crumble.downloader.IDownloader;
import se.chalmers.tda366.crumble.downloader.impl.Downloader;
import se.chalmers.tda366.crumble.utils.IObservable;


public class DownloadThread extends Thread implements Serializable, IObservable{
	private List<IFeed> feeds;
	private final PropertyChangeSupport observers = new PropertyChangeSupport(
            this);
	
	// Empty construct if launch failed to load existing feeds from user home
	public DownloadThread () {
		feeds = new ArrayList<IFeed>();
	}
	
	// Construct for existing feeds
	public DownloadThread (List<IFeed> feeds) {
		this.feeds = feeds;
	}
	
	// Add the feed to downloadthread when user adds feed
	public void addFeed (IFeed feed) {
		synchronized(feeds){
			feeds.add(feed);
		}
	}
	
	public void run() {
		while(true)
		{
			// Notify controller that download has started
			observers.firePropertyChange("DLFIN", 1, 0);
			synchronized(feeds){
				for (IFeed feed : feeds)
				{
					IDownloader downloader = new Downloader(feed);
					ArrayList<IArticle> newArts = downloader.getFeed();
					feed.setArticles(newArts);
				}	
			}
			// Notify controller that download has ended
			observers.firePropertyChange("DLFIN", 0, 1);
			
			// Sleep 10minutes between each download
			try {
				Thread.sleep(600000);
			} catch (InterruptedException e) {
				
			}	
		}
	}

    @Override
    public void addPropertyChangeListener(PropertyChangeListener observer) {
            observers.addPropertyChangeListener(observer);
    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener observer) {
            observers.removePropertyChangeListener(observer);
    }
}
